package cn.kgc.fxy.smbms.web;

import cn.kgc.fxy.smbms.entity.Provider;
import cn.kgc.fxy.smbms.entity.User;
import cn.kgc.fxy.smbms.service.Constant;
import cn.kgc.fxy.smbms.service.ProviderService;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

@Controller
@RequestMapping("provider")
public class ProviderController {
    @Resource
    private ProviderService providerService;
    @RequestMapping("/show")
    public String show(Provider condition, Integer pageNum, Model model){
        Integer pageSize = 5;
        PageInfo<Provider> providerPageInfo = this.providerService.findProvider(condition,pageNum,pageSize);
        model.addAttribute("pageInfo",providerPageInfo);
        return "provider/list";
    }

    @RequestMapping("view")
    public String view(Long proId,Model model){
        Provider provider = this.providerService.findView(proId);
        model.addAttribute("provider",provider);
        return "provider/view";
    }

    @RequestMapping("/toAdd")
    public String toAdd(){

        return "provider/add";
    }
    @RequestMapping("/doAdd")
    public String doAdd(@Valid Provider provider, BindingResult bindingResult, HttpSession session){
        if (bindingResult.hasErrors()){
            return "provider/add";
        }

        User loginUser = (User) session.getAttribute(Constant.USER);
        System.out.println("loginUser = " + loginUser);
        provider.setCreatedBy(loginUser);
        this.providerService.addProvider(provider);
        return "redirect:show";
    }
    @RequestMapping("/showProviderCount")
    @ResponseBody
    public String showProviderCount(String proCode){
        Integer providerCount = providerService.findProviderCount(proCode);
        return providerCount.toString();
    }

    @RequestMapping("/toModify")
    public String toModify(Long proId,Model model){
        Provider provider=providerService.findView(proId);
        model.addAttribute("provider",provider);
        return "provider/modify";
    }
    @RequestMapping("/doModify")
    public String doModify(@Valid Provider provider,BindingResult bindingResult){
        if (bindingResult.hasErrors()){

            return "provider/modify";
        }
        providerService.modifyProvider(provider);
        return "redirect:show";
    }

    @RequestMapping("toRemove")
    public String toRemove(Long proId){
        providerService.removeProvider(proId);
        return "redirect:show";
    }
}
